package com.sky.service.impl;

import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.utils.WeChatUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WeChatUtils weChatUtil;


    /**
     * 登录
     *
     * 1根据appid appsecret code 获取用户的openId
     * 2将apenI(用户的唯一表示)保存到User表
     * 3获取用户的ID,生成JWT
     * 4封装UserLoginVo返回
     * @param code
     * @return
     */
    @Override
    public UserLoginVO wxlogin(String code){
        try {
            //获取用户登录的openId
            String openId = weChatUtil.getOpenId(code);

            //入库

            //查询是否入库
            User user = userMapper.findOpenIdUser(openId);
            if (user == null){
                user =  new User();
                user.setOpenid(openId);
                user.setCreateTime(LocalDateTime.now());
                //用户openId入user库
                userMapper.insertUser(user);
            }
            //得到UserId,生成JWT
            Long userId = user.getId();
            HashMap<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID,userId);
            String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
            //封装UserLoginVO返回
            return UserLoginVO.builder()
                    .id(userId)
                    .openid(openId)
                    .token(jwt)
                    .build();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
